import { mapGetters } from 'vuex'
import { upsert, detailOne, IUpsertParams, IDetailOneParams } from '@/api/commonInstance'
import { DBNames } from '@/enum/dbName'
import { deepCopy } from '@/utils/tool'

export interface ISelectKey {
  key: string
  options: string
}

export interface IOptions {
  label: string
  value: string
}
export interface ITreeKey {
  key: string
  refName: string
}

export interface IAddEditMixinParams {
  treeKey?: ITreeKey[]
  selectKey?: ISelectKey[]
  templateName: string
}

export default (params: IAddEditMixinParams) => {
  const { selectKey, treeKey, defaultForm, templateName } = params

  const mixin = {
    props: {
      parkId: {
        type: String,
        default: '',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        templateName: DBNames[templateName],
        loading: false, // 加载状态
        isShowMap: false, // 地图选点组件状态
        formAll: {}, // 全部字段的拷贝
      }
    },

    mounted() {},
    methods: {
      async getDetail(params: IDetailOneParams) {
        // @ts-ignore
        this.loading = true
        const result = await detailOne(params)
        // @ts-ignore
        this.id = params.id
        this.initForm(result.data)
        // @ts-ignore
        this.loading = false
      },

      initForm(data: any) {
        console.log('initForm')
        // @ts-ignore
        this.formAll = deepCopy(data)
        const { form } = this as any
        Object.keys(form).forEach((key) => {
          // @ts-ignore
          const value = this.formAll[key]
          if (value) {
            form[key] = value
          }
        })
      },

      handleSave() {
        const { formAll, form, portalId, templateName, parkId } = this as any

        // @ts-ignore
        this.$refs.ruleForm.validate(async (valid: boolean) => {
          if (valid) {
            // @ts-ignore
            this.loading = true

            const id = parkId || portalId

            const params: IUpsertParams = {
              data: { ...formAll, ...form },
              templateName,
            }

            if (id) {
              params.id = id
            }

            await upsert(params)
            // @ts-ignore
            this.loading = false
            // @ts-ignore
            this.$emit('onRefresh')
            // @ts-ignore
            this.$message.success('保存成功！')
          }
        })
      },

      handleCloseDialog() {
        // @ts-ignore
        this.$refs.ruleForm?.resetFields()
      },

      handleAddContacts() {
        // @ts-ignore
        this.form.contacts.push({
          name: '',
          phone: '',
        })
      },

      handleDelContacts(index: number) {
        // @ts-ignore
        this.form.contacts.splice(index + 1, 1)
      },

      handleAddHonor() {
        // @ts-ignore
        this.form.parkHonor.push({
          name: '',
          phone: '',
        })
      },

      handleDelHonor(index: number) {
        // @ts-ignore
        this.form.parkHonor.splice(index + 1, 1)
      },

      handleIndustryChange() {},
      handlePreview() {},
    },
    computed: {
      ...mapGetters('tree', {
        industryTree: 'industryTag',
        areaTree: 'area',
      }),
      ...mapGetters('portal', ['portalId', 'portalData']),
    },
    watch: {
      'form.addrs'(val: string) {
        if (val) {
          // @ts-ignore
          this.$refs.ruleForm.validateField('addrs')
        }
      },
      portalId: {
        immediate: true,
        handler(id: number) {
          console.log('portalId', id)

          if (id) {
            // @ts-ignore
            this.initForm(this.portalData)
          }
        },
      },
      // parkId: {
      //   immediate: true,
      //   handler(parkId: string) {
      //     console.log('parkId', parkId)
      //     // @ts-ignore
      //     this.$refs.ruleForm?.resetFields()
      //     // @ts-ignore
      //     this.form = { ...defaultForm }
      //   },
      // },
    },
  }

  if (selectKey) {
    selectKey.forEach((d) => {
      mixin.watch[`form.${d.key}`] = function (val: string) {
        if (Array.isArray(val)) {
          const labels = val.map((l) => {
            // @ts-ignore
            const obj = this[d.options]?.find((o: IOptions) => o.value === l)
            return obj?.label
          })
          // @ts-ignore
          this.form[`${d.key}Label`] = labels
        } else {
          // @ts-ignore
          const obj = this[d.options]?.find((o: IOptions) => o.value === val)
          // @ts-ignore
          this.form[`${d.key}Label`] = obj?.label
        }
      }
    })
  }

  if (treeKey) {
    treeKey.forEach((d) => {
      mixin.watch[`form.${d.key}`] = function () {
        // @ts-ignore
        const nodes = this.$refs[d.refName].getCheckedNodes()
        // @ts-ignore
        this.form[`${d.key}Label`] = nodes.map((n) => n.label)
      }
    })
  }

  return mixin
}
